<template>
  <div class="fullschedule-container" ref="fullscheduleContainer" :style="fscStyle">
    <div class="fsc-root">
      <fscheader :week-arr="weekArr"></fscheader>
      <div class="fsc-container">
        <fscmain
          v-if="scheduledata"
          :scheduledata="scheduledata"
        ></fscmain>
        <div v-else class="ky-listnone">暂无数据~</div>
      </div>
    </div>
  </div>
</template>
<!--
  预约排班组件
  rowHeight 设置 显示的行高
  isEdit 设置是否可以编辑 默认 true
  isAdd 设置 是否可以新增 默认 true
  delSend 设置 是否可以删除时段模板
  checkboxShow  设置 头部是否显示复选框
  statusFilter 设置 判断需要显示的数据，跟时段状态对应
  statusTemplate 设置模板类型:
    schedule:编辑类型，预约排班设置时的模板
    template:模板类型，视图模板、已发布排班模板、导入查看模板
-->
<script>
// import bus from '@/api/bus'
import { mapGetters } from 'vuex'
import { getHolidayList } from '@/api/api'
// import { setLocalStorage } from '@/utils/localStorage' // removeLocalStorage
import { getSidebarData, getSidebarDataTemp } from '@/utils/utils'
import fscheader from './fscheader'
import fscmain from './fscmain'
import {
  getWeekStartEndDate,
  calMaxMinTime,
  calAppoInitialNum,
  calNewAppoTime,
  calTimeSelected,
  getCalTimeMinute,
  getInitTimeGroud,
  calAppoStyleObj,
  getArgsCalNum,
  getSeasonDateInfo,
  getSeasonDateTitle,
  getAppointmentSametype,
  getScheduleAppoSametype,
  getAppointmentSametypeOnline,
  getScheduleAppoSametypeOnline,
  flattenDeep,
  getSeasonDefault,
  getContinuityNum,
  timeTransferInterval
} from '@/utils/schedule'

import { dateFormatter } from '@/utils/validate'
const originObj = {
  // appoSize: 'normal', // mini\ normal
  'id': 0,
  'hospitalCode': '', // 医院编号
  'recordCode': '', // 编码
  'depArea': '', // 影像区域
  'dep': '', // 检查部门
  'modality': '', // 检查设备
  'checkRoom': '', // 检查机房
  'appointmentDate': '', // 检查日期
  'week': '', // 星期几
  'checkClass': '', // 检查班次
  'beginTime': '', // 检查开始时间
  'endTime': '', // 检查结束时间
  'initialNum': 0, // 初始号码
  'checkNum': 0, // 检查数量
  'reserveNum': 0, // 预留数量
  'addNum': 0, // 追加数量
  'callNum': 0, // 已预约数量
  'totalNum': 0, // 号源总数
  'color': '', // 颜色
  'operatorName': '', // 操作人
  'operatorDate': '', // 操作时间
  'appointmentStatus': '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班
  'remark1': '',
  'remark2': '',
  'remark3': '',
  'season': '1', // 时令
  'department': '' // 所属科室
}
// const timegatherLineObj = {
//   height: 60,
//   heightpx: '84px',
//   preKey: '',
//   startNum: 1,
//   time: '00:00-24:00'
// }
export default {
  components: {
    fscmain,
    fscheader
  },
  props: {
    weekArr: {
      type: Array,
      default() {
        return []
      }
    },
    rowHeight: {
      type: Number,
      default: 64
    },
    // 预约时段列表，显示为左边菜单
    scheduledata: {
      type: Array,
      default() {
        return []
      }
    },
    // 快速排班的号源条件模板数据
    quickTempObj: {
      type: Object,
      default: null
    },
    // 是否可编辑
    isEdit: {
      type: Boolean,
      default: true
    },
    // 是否可复制
    isCopy: {
      type: Boolean,
      default: false
    },
    // 是否可新增
    isAdd: {
      type: Boolean,
      default: true
    },
    // 是否强制显示所有日期可选
    allCkb: {
      type: Boolean,
      default: false
    },
    // 是否显示头部编辑图标
    editShow: {
      type: Boolean,
      default: false
    },
    // 是否显示头部复选框
    checkboxShow: {
      type: Boolean,
      default: false
    },
    // 判断需要显示的数据
    statusFilter: {
      type: String,
      default: ''
    },
    statusTemplate: {
      type: String,
      default: 'schedule'
    },
    delSend: {
      type: Boolean,
      default: false
    },
    from: {
      type: String,
      default: ''
    },
    hospitalCode: {
      type: String,
      default: ''
    },
    // 模板排列，定位、日按顺序排
    appoRepair: {
      type: Boolean,
      default: false
    }
    // appoContinuation: {
    //   // 判断号源是否连续设置
    //   type: Boolean,
    //   default: false
    // }
  },
  data() {
    return {
      fscStyle: { height: 'calc(100vh - 320px)' },
      isChanged: false, // 判断模板数据是否有修改，提交时可以做拦截判断提示
      currDate: dateFormatter(new Date(), false),
      curWeekDate: '',
      checkedAll: false,
      week: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
      seasonCur: '',
      // sidebardata: [],
      monthHoliday: {},
      weekDate: [], // 一周的日期,计算出来后在表格头部展示
      /**
       * 预约时段,号源的主体数据
       * date：日期
       * week: 星期
       * holiday: 节假日
       * season: 时令 1：冬令时，2：夏令时
       * disable: 今天是否可编辑
       * checkedAll: 是否全选当前日期整列
       * rest: 是否是否休息
       * appointmentTotal: 号源总是
       * appointment：预约时段数据列表, 数据格式: [时段 [时间段 [时段号源数据 {}]]]
      */
      // scheduledata: [],
      quickTempObjFul: null, // 判断最初开发时，模拟加数据

      // 当前选择坐标暂存数据
      sidebarIndex: null,
      scheduleIndex: null,
      appoIndex: null,
      timeIndex: null,

      appoFormData: {
        HospitalCode: '',
        StartDate: '',
        EndDate: '',
        DepArea: '',
        Dep: '',
        Modality: '',
        ModalityType: '',
        CheckRoom: '',
        AppointmentStatus: '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班；单选
        IsHasFilters: true
      },
      isCheckedIds: []
    }
  },
  computed: {
    ...mapGetters(['appoContinuation', 'isContinuityNum'])
  },
  created() {
    // console.log('checkboxShow_in_index.vue--created', this.checkboxShow)
    // this.init(this.newDate)
    // console.log('进入 fullschedule Page')
  },
  mounted() {
    // console.log('checkboxShow_in_index.vue--mounted', this.checkboxShow)
    // console.log('打印scheduledata', this.scheduledata)
  },
  methods: {
    // item勾选状态改变
    checkBoxChange(data) {
      // console.log('勾选状态改变', data)
      const { isChecked, scheduleIndex, sidebarIndex, appoIndex } = data
      let id = this.scheduledata[scheduleIndex].appointment[sidebarIndex][appoIndex].id
      // console.log('this.scheduledata[scheduleIndex].appointment[sidebarIndex]', this.scheduledata[scheduleIndex].appointment[sidebarIndex])
      // console.log('id', id)
      // this.isCheckedIds 所多选的号源id，用来判断当前是否多选
      if (!isChecked) {
        // 如果有一个不勾选，header的checkbox也为不勾选
        this.scheduledata[scheduleIndex].checkedAll = false
        let idIndex = this.isCheckedIds.indexOf(id)
        if (idIndex > -1) {
          this.isCheckedIds.splice(idIndex, 1)
        }
      } else {
        this.isCheckedIds.push(id)
      }
      // console.log('this.isCheckedIds', this.isCheckedIds)
      // console.log('然后改变列表值，然后再传入item')
      this.scheduledata[scheduleIndex].appointment[sidebarIndex][appoIndex].isChecked = isChecked
      // 判断是否勾选/取消勾选header的全选checkbox
      let isAllChecked = true
      this.scheduledata[scheduleIndex].appointment.forEach(checkClassData => {
        checkClassData.forEach(item => {
          if (!item.isChecked && !item.isAddBox) {
            isAllChecked = false
          }
        })
      })
      // console.log('isAllChecked', isAllChecked)
      // 如果遍历当天所有的号源后，isAllChecked依然是true,则header的checkbox勾选，否则不勾选
      if (isAllChecked) {
        this.scheduledata[scheduleIndex].checkedAll = true
      } else {
        this.scheduledata[scheduleIndex].checkedAll = false
      }
      // console.log('this.scheduledata[scheduleIndex].checkedAll', this.scheduledata[scheduleIndex].checkedAll)
      console.log('改变后的scheduledata', this.scheduledata)
    },
    // 列全选
    HeaderColAll(data) {
      const { index } = data
      this.scheduledata[index].checkedAll = !this.scheduledata[index].checkedAll
      // 然后，还需要把appointment里面的每个时段的号源都勾选一下，就是isChecked都设置为true
      this.scheduledata[index].appointment.forEach(timeFrameData => {
        timeFrameData.forEach(item => {
          // 排除【新增号源】按钮
          if (!item.isAddBox) {
            item.isChecked = this.scheduledata[index].checkedAll
            // this.isCheckedIds 所多选的号源id，用来判断当前是否多选
            let id = item.id
            if (this.scheduledata[index].checkedAll) {
              let idIndex = this.isCheckedIds.indexOf(id)
              if (idIndex == -1) {
                this.isCheckedIds.push(id)
              }
            } else {
              let idIndex = this.isCheckedIds.indexOf(id)
              if (idIndex > -1) {
                this.isCheckedIds.splice(idIndex, 1)
              }
            }
          }
        })
      })
      // console.log('this.isCheckedIds', this.isCheckedIds)
      this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      // console.log('this.scheduledata', this.scheduledata)
      this.headerCheckedAllChange(false)
      // this.$forceUpdate()
    },
    // 全选
    headerCheckedAllChange(change) {
      console.log('headerCheckedAllChange111', this.scheduledata)
      let ckb = true
      this.scheduledata.forEach(item => {
        if (!item.disable || this.allCkb) {
          if (change) {
            item.checkedAll = this.checkedAll
          } else if (!item.checkedAll) {
            ckb = false
          }
        }
      })
      if (change) {
        this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      } else {
        this.checkedAll = ckb
      }
      console.log('headerCheckedAllChange222', this.scheduledata)
      this.$emit('checkedAllChange')
    },
    // 编辑|查看详情, 预约号源
    appoClick(data) {
      console.log('编辑|查看详情, 预约号源appoClick_data', data) // timeIndex
      const { sidebarIndex, scheduleIndex, appoIndex, sItem } = data.info
      this.sidebarIndex = sidebarIndex
      this.scheduleIndex = scheduleIndex
      this.appoIndex = appoIndex
      // console.log('sidebarIndex', sidebarIndex)
      // console.log('this.sidebardata[sidebarIndex]', this.sidebardata[sidebarIndex])
      // console.log('appoClick:=====', sidebarIndex, scheduleIndex, appoIndex, sItem)
      // const tg = appoNew || this.sidebardata[sidebarIndex].timegather[scheduleIndex]
      // // console.log('tg', tg)
      let _time = sItem.beginTime + '-' + sItem.endTime
      const _startTime = this.appoRepair ? '00:00' : this.sidebardata[sidebarIndex].start
      const _endTime = this.appoRepair ? '24:00' : this.sidebardata[sidebarIndex].end
      const _disable = this.scheduledata[scheduleIndex].disable
      // 去除当前数据
      const appos = this.scheduledata[scheduleIndex].appointment[sidebarIndex]
      const appoArr = JSON.parse(JSON.stringify(appos))
      const curAppoIndex = appoArr.findIndex(appoItem => appoItem.beginTime === sItem.beginTime && appoItem.endTime === sItem.endTime)
      if (curAppoIndex >= 0) {
        this.timeIndex = curAppoIndex
        appoArr.splice(curAppoIndex, 1)
      }
      // 计算当前时间段可选择的时间范围
      _time = calMaxMinTime(_time, appoArr, _startTime, _endTime)
      // console.log('appoClick appoArr', appoArr)
      // console.log('appoClick _time', _time)
      // console.log('_startTime, _endTime', _startTime, _endTime)
      // const timeOpt = calMaxMinTime(_time, appos, _startTime, _endTime)
      const timeSel = this.sidebardata[sidebarIndex].start + '-' + this.sidebardata[sidebarIndex].end// '08:00-12:00'
      // console.log('timeSel in click edit', timeSel)
      this.$emit('handleAppoInfo', { appoInfo: sItem, timeSel: timeSel, time: _time, disableDate: _disable, isCheckedIds: this.isCheckedIds })
    },
    // 新增，排班
    async appoAdd(data) {
      console.log('新增按钮触发，排班appoAdd')
      const { sidebarIndex, scheduleIndex, timeIndex, appoNew } = data
      this.sidebarIndex = sidebarIndex
      this.scheduleIndex = scheduleIndex
      this.timeIndex = timeIndex
      this.appoIndex = null
      // console.log('sidebarIndex====>', sidebarIndex)
      // console.log('this.sidebardata====>', this.sidebardata)
      const tg = appoNew || this.sidebardata[sidebarIndex].timegather[timeIndex]
      const seasonInfo = getSeasonDateInfo(this.scheduledata[scheduleIndex], tg.time)
      const startNum = this.statusTemplate !== 'template' ? seasonInfo ? seasonInfo.startNum : tg.startNum : tg.startNum
      const _startTime = this.appoRepair ? '00:00' : this.sidebardata[sidebarIndex].start
      const _endTime = this.appoRepair ? '24:00' : this.sidebardata[sidebarIndex].end
      // // console.log('appoAdd:====', sidebarIndex, scheduleIndex, timeIndex)
      if (!this.quickTempObj && !this.quickTempObjFul) {
        let _time = tg.time
        const _week = this.week[scheduleIndex]
        const _checkClass = this.sidebardata[sidebarIndex].title
        // 计算当前时间段可选择的时间范围
        const appos = this.appoRepair ? this.scheduledata[scheduleIndex].appointment : this.scheduledata[scheduleIndex].appointment[sidebarIndex]
        const timeOpt = calMaxMinTime(_time, appos, _startTime, _endTime)
        const timeSel = calTimeSelected(_time, timeOpt) // '08:00-12:00'
        // console.log('appoAdd in fullschedule——————timeSel', timeSel)
        // console.log('appoAdd in fullschedule', _time, appos, _startTime, _endTime)
        // 没有快捷模板，新增预约时段号源。弹出框进行设置
        this.$emit('addNewSchedule', { time: timeOpt, timeSel: timeSel, week: _week, checkClass: _checkClass, startNum: startNum })
        return
      }
      // 有选择快捷模板，直接用快捷模板数据赋值
      const nObj = Object.assign({}, this.quickTempObj)
      const dateAppoData = this.scheduledata[scheduleIndex]
      const appoArr = this.scheduledata[scheduleIndex].appointment[sidebarIndex]
      // 设置初始号码，设置时段获取的时段初始号码
      nObj.initialNum = startNum * 1 // 初始号码
      nObj.startNum = startNum * 1
      nObj.preKey = tg.preKey
      if (this.quickTempObj) {
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
        let _time = tg.time
        const etime = timeTransferInterval(nObj.beginTime, nObj.endTime, _time.split('-')[0])
        // console.log('etimeetimeetimeetime', etime)
        nObj.id = 0
        nObj.timestamp = new Date().getTime() + Math.random()
        nObj.secTime = etime
        nObj.beginTime = _time.split('-')[0]
        nObj.endTime = _time.split('-')[1]
        nObj.week = this.week[scheduleIndex]
        // nObj.initialNum = 0
        nObj.addNum = 0 // 追加设置 为0
        nObj.checkNum = nObj.checkNum * 1 // 检查数量
        nObj.reserveNum = nObj.reserveNum * 1 // 预留数量
        nObj.callNum = nObj.callNum * 1 // 已预约数量
        nObj.remark2 = nObj.recordCode
        nObj.status = '启用' // 状态
        nObj.appointmentStatus = ''
        nObj.appointmentDate = dateAppoData.dateFull + ' 00:00:00'
        nObj.checkClass = this.sidebardata[sidebarIndex].title
      }
      // // console.log('appoArr=======>12345678', appoArr)
      // 计算当前添加参数模板的班次时间
      const _nObj = await calNewAppoTime(appoArr, nObj, _startTime, _endTime)
      // console.log('this.sidebardata[sidebarIndex]', this.sidebardata[sidebarIndex])
      // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[sidebarIndex]
      const timeObj = this.sidebardata[sidebarIndex]
      const nnobj = calAppoStyleObj(timeObj, _nObj, this.rowHeight)
      if (nnobj) {
        // 班次名称判断转换
        const appoTitle = getSeasonDateTitle({
          appointmentDate: nnobj.appointmentDate,
          beginTime: nnobj.beginTime,
          endTime: nnobj.endTime,
          checkClassData: this.sidebardata
        })
        nnobj.checkClass = appoTitle || nnobj.checkClass
        const _appoArr = appoArr ? appoArr.concat([nnobj]) : [nnobj]
        // 获取排班号源初始号码排序数据
        this.scheduledata[scheduleIndex].appointment[sidebarIndex] = _appoArr
        const resSche = await this.getAppoByTypes(this.scheduledata[scheduleIndex].appointment, nnobj.checkClass, this.scheduledata[this.scheduleIndex].dateFull)
        this.scheduledata[scheduleIndex].appointment = resSche
        this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
      }
    },
    getAppoByTypes(a, b, d) {
      return new Promise(async resolve => {
        console.log('this.appoRepair', this.appoRepair) // this.appoRepair = true
        const resAppo = this.appoRepair
          ? await getAppointmentSametypeOnline(a, this.appoContinuation, this.sidebardata, d)
          : await getAppointmentSametype(a, b, this.appoContinuation, this.sidebardata, d)
        resolve(resAppo)
      })
    },
    /**
     * @param {Object} a 一周的号源模板数据
     * @param {Object} _sbData
     */
    getScheByTypes(a, _sbData) {
      // console.log('=======in getScheByTypes=======')
      // console.log('a', a)
      // console.log('_sbData', _sbData)
      // console.log('this.appoRepair', this.appoRepair)
      return new Promise(async resolve => {
        // checkClassData 排班列表竖向的时间维度
        // getScheduleAppoSametypeOnline(scheduledata, continuation, checkClassData)
        // console.log('打印排班列表竖向的时间维度=>this.sidebardata', this.sidebardata)
        const resSche = this.appoRepair
          ? await getScheduleAppoSametypeOnline(a, this.appoContinuation, _sbData || this.sidebardata) // 现在都是使用这个函数
          : await getScheduleAppoSametype(a, this.appoContinuation, _sbData || this.sidebardata) // 该函数返回不了数据，有问题
        // const resSche = await getScheduleAppoSametypeOnline(a, this.appoContinuation, _sbData || this.sidebardata)
        resolve(resSche)
      })
    },
    // 时间出错的数据回写判断
    insertError(errordata) {
      return new Promise(async resolve => {
        // console.log('errordata', errordata)
        const appoOldData = JSON.parse(JSON.stringify(this.scheduledata))
        const insertData = JSON.parse(JSON.stringify(errordata))
        let insertLen = insertData.length
        const _week = this.week
        const errorList = []
        if (insertLen === 0) {
          resolve()
          return
        }
        const insertRun = async () => {
          const iAppo = insertData.shift()
          if (insertLen === 0 && !iAppo) {
            // 结束
            // console.log('errorList:', errorList)
            this.scheduledata = await this.getScheByTypes(appoOldData)
            this.$emit('appoErrorListChange', errorList)
            this.isChanged = true
            resolve()
            return
          }
          try {
            // 错误的数据获取不到 sidebarIndex，需要重新计算
            let sidebarIndex = this.calSidebarIndex(iAppo)
            // 判断日期，获取日期索引
            let scheduleIndex = _week.findIndex(w => w === iAppo.week)
            if (sidebarIndex < 0 || scheduleIndex < 0) {
              errorList.push(iAppo)
              return
            }
            const _startTime = this.sidebardata[sidebarIndex].start
            const _endTime = this.sidebardata[sidebarIndex].end
            let appoArr = appoOldData[scheduleIndex].appointment[sidebarIndex]
            let insertTime = iAppo.beginTime + '-' + iAppo.endTime
            // 计算时段号源在当前时段区间内的可设置的时间段区间
            const appos = this.appoRepair ? appoOldData[scheduleIndex].appointment : appoOldData[scheduleIndex].appointment[sidebarIndex]
            const _time = calMaxMinTime(insertTime, appos, _startTime, _endTime)
            if (_time) {
              // const nObj = Object.assign({}, iAppo)
              // const oObj = appoOldData[scheduleIndex].appointment[sidebarIndex]
              // 新老号源时间段对比
              const oTs = getCalTimeMinute(iAppo.beginTime)
              const oTe = getCalTimeMinute(iAppo.endTime)
              const nTs = getCalTimeMinute(_time.split('-')[0])
              const nTe = getCalTimeMinute(_time.split('-')[1])
              // // console.log(oTs, oTe)
              // // console.log(nTs, nTe)
              if (oTs >= nTs && oTe <= nTe) {
                // 时段号源的时间段在时间区间内
                iAppo.isBad = false
                // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[sidebarIndex]
                const timeObj = this.sidebardata[sidebarIndex]
                const nnobj = calAppoStyleObj(timeObj, iAppo, this.rowHeight)
                if (nnobj) {
                  appoArr = appoArr ? appoArr.concat([nnobj]) : [nnobj]
                  appoOldData[scheduleIndex].appointment[sidebarIndex] = appoArr
                }
              } else {
                // 时段号源的时间段超出时间区间
                errorList.push(iAppo)
              }
            } else {
              // 时段号源的时间段超出时间区间
              iAppo.oldBeginTime = iAppo.beginTime
              iAppo.oldEndTime = iAppo.endTime
              errorList.push(iAppo)
            }
          } catch (err) {
            // console.log(err)
            errorList.push(iAppo)
          }
        }
        // 开始执行任务
        while (insertLen >= 0) {
          insertRun()
          insertLen -= 1
        }
      })
    },
    // 删除,预约号源
    async appoDel(data) {
      const { sidebarIndex, scheduleIndex, appoIndex, sItem } = data
      // console.log(`appoDel=>sidebarIndex:${sidebarIndex},scheduleIndex:${scheduleIndex},appoIndex:${appoIndex},sItem:${sItem}`)
      this.sidebarIndex = sidebarIndex
      this.scheduleIndex = scheduleIndex
      this.appoIndex = appoIndex
      if (sItem.id && this.delSend) {
        this.$emit('handleAppoDel', sItem)
      } else {
        if (this.scheduledata[scheduleIndex].appointment[sidebarIndex].length > 0) {
          this.scheduledata[scheduleIndex].appointment[sidebarIndex].splice(appoIndex, 1)
        }
        const resSche = await this.getScheByTypes(this.scheduledata)
        // console.log('resSch', resSche)
        this.scheduledata = JSON.parse(JSON.stringify(resSche))
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
      }
    },
    appoDelSuccessCb() {
      this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex].splice(this.appoIndex, 1)
      // 计算预约号源的当天总数
      this.calAppoTotal(this.scheduledata)
      // 判断为已改变，提交时做判断是否提交更新
      this.isChanged = true
    },
    // 复制其他日期的时段号源
    copyInsert(data) {
      this.$emit('copyInsertChange', data)
    },
    // 时令切换，班次时间段更新
    async seasonChange(season) {
      // console.log(season)
      // const resSeason = await getSeasonSchedule(season)
      // console.log('获取时间轴getSeasonSchedule', resSeason)
      const _sidebardata = getSidebarData() || getSidebarDataTemp() // resSeason.sidebardata
      // 班次时段更新
      await this.initSidebar(_sidebardata)
      // 号源重新插入
      let appodata = []
      this.scheduledata.forEach(sche => {
        let iScheAppoArr = sche.appointment
        iScheAppoArr = flattenDeep(iScheAppoArr)
        appodata.push(iScheAppoArr)
      })
      appodata = flattenDeep(appodata)
      this.appoPull(appodata, true)
    },
    resetAppoStatus(status, from) {
      this.scheduledata.forEach(item => {
        const appos = item.appointment
        // console.log('777888item.checkedAll', item.checkedAll)
        if (item.checkedAll) {
          appos.forEach(appoSche => {
            appoSche.forEach(appo => {
              // if (appo.appointmentStatus !== '正常预约') {
              //   appo.appointmentStatus = status
              // }
              if (from == 'temp') {
                appo.status = status
                // console.log('appo.status', appo.status)
              } else {
                appo.appointmentStatus = status
                // console.log('appo.appointmentStatus', appo.appointmentStatus)
              }
            })
          })
        }
      })
      // console.log('this.scheduledata', this.scheduledata)
      // this.appoPull(this.scheduledata)
      // 判断为已改变，提交时做判断是否提交更新
      this.isChanged = true
    },
    // 同步时令设置时段参数
    appoSyncSet() {
      // console.log('同步时令设置时段参数')
      this.isChanged = true
      const seasonInfo = getSeasonDefault()
      const isCN = getContinuityNum()
      // // console.log(seasonInfo)
      // 获取第一个时段 班次
      const getCheckClass = (appointment) => {
        let cc = ''
        let idx = -1
        const len = appointment.length
        for (let i = 0; i < len; i++) {
          const appos = appointment[i]
          if (appos.length > 0) {
            cc = appos[0].checkClass
            idx = i
            return { cc: cc, idx: idx }
          }
        }
        return { cc: cc, idx: idx }
      }
      // 获取时令班次初始号码
      const getInitialNum = (checkClass) => {
        let startNum = ''
        const sdObj = seasonInfo.checkClassSettings[`${checkClass}`]
        if (sdObj) {
          const sdd = sdObj.numberSettings
          startNum = sdd ? sdd[0].startNum : ''
        }
        return startNum
      }

      // // console.log(JSON.parse(JSON.stringify(this.scheduledata)))
      this.scheduledata.forEach(async sche => {
        if (isCN) {
          const { cc, idx } = getCheckClass(sche.appointment)
          const startNum = getInitialNum(cc)
          // // console.log(startNum)
          if (startNum >= 0 && idx >= 0) {
            sche.appointment[idx][0].initialNum = startNum
            sche.appointment = await this.getAppoByTypes(sche.appointment, cc, sche.dateFull)
          }
        } else {
          let keys = {}
          let scheAppos = JSON.parse(JSON.stringify(sche.appointment))
          scheAppos.forEach(async (appos, scheIdx) => {
            if (appos.length > 0) {
              let cc = ''
              appos.forEach(appo => {
                if (!keys[`${appo.checkClass}`]) {
                  keys[`${appo.checkClass}`] = true
                  cc = appo.checkClass
                  const startNum = getInitialNum(appo.checkClass)
                  // console.log(startNum)
                  if (startNum >= 0) {
                    appo.initialNum = startNum
                  }
                }
              })
              if (cc) {
                sche.appointment = await this.getAppoByTypes(scheAppos, cc, sche.dateFull)
              }
            }
          })
        }
      })
      // console.log('解析后的scheduledata数据', JSON.parse(JSON.stringify(this.scheduledata)))
    },
    // 删除选中日期的所有号源
    async appoDelDay() {
      this.isChanged = true
      let _sidebardata = this.sidebardata
      this.scheduledata.forEach(sche => {
        if (sche.checkedAll) {
          sche.appointment = this.getAppointentArr(_sidebardata)
        }
      })
      const resSche = await this.getScheByTypes(this.scheduledata)
      this.scheduledata = JSON.parse(JSON.stringify(resSche))
      // this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
    },
    // 添加新的排班号源
    async addNew(appoObj, isTemp) {
      console.log('addNew=>appoObj', appoObj)
      let sidebarDasta = isTemp ? getSidebarDataTemp() : getSidebarData()
      // 这里需要判断号源的班次
      const appoTitle = getSeasonDateTitle({
        appointmentDate: null,
        beginTime: appoObj.beginTime,
        endTime: appoObj.endTime,
        checkClassData: sidebarDasta
      })
      appoObj.checkClass = appoTitle
      sidebarDasta.forEach((item, index) => {
        if (item.title == appoObj.checkClass) {
          this.sidebarIndex = index
        }
      })
      // if (appoObj.checkClass == '凌晨班') {
      //   this.sidebarIndex = 0
      // } else if (appoObj.checkClass == '上午班') {
      //   this.sidebarIndex = 1
      // } else if (appoObj.checkClass == '下午班') {
      //   this.sidebarIndex = 2
      // }
      // console.log('添加单条号源点确定按钮后触发addNew函数appoObj', appoObj)
      // console.log('这里拿到的号源里已经改变了班次名称，需往上找原因')
      const _obj = Object.assign({}, appoObj)
      // console.log(`beginTime~endTime:${_obj.beginTime}~${_obj.endTime}`)
      // console.log('++++++++++++++添加新的排班号源addNew————_obj', _obj)
      this.appoIndex = null
      // console.log(`把this.scheduledata[${this.scheduleIndex}].appointment[${this.sidebarIndex}]赋值给appoData`)
      // console.log('this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]', this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex])
      let appoData = [...this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]]
      // console.log('appoData——concat之前--刚刚赋值过来', appoData)
      // console.log('this.sidebarIndex', this.sidebarIndex)
      // console.log('this.sidebardata[this.sidebarIndex]', this.sidebardata[this.sidebarIndex])
      // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[this.sidebarIndex] // 原来是这句
      const timeObj = this.sidebardata[this.sidebarIndex] // 20231102修改后用这句
      // console.log('当前时间轴timeObj', timeObj)
      // console.log('然后要把_obj经过calAppoStyleObj函数加工赋值给nnobj')
      // console.log(`beginTime~endTime:${_obj.beginTime}~${_obj.endTime}`)
      const nnobj = calAppoStyleObj(timeObj, _obj, this.rowHeight)
      // console.log('然后要把nnobj合并到appoData中')
      // console.log('+++++++++++++++++添加号源nnobj++++++++++++++++++', nnobj)
      if (nnobj) {
        const dateAppoData = this.scheduledata[this.scheduleIndex]
        nnobj.id = 0
        nnobj.timestamp = new Date().getTime() + Math.random()
        nnobj.week = this.week[this.scheduleIndex]
        nnobj.addNum = 0 // 追加设置 为0
        nnobj.status = nnobj.status ? nnobj.status : '启动' // 状态
        nnobj.appointmentStatus = nnobj.appointmentStatus ? nnobj.appointmentStatus : ''
        nnobj.appointmentDate = dateAppoData.dateFull + ' 00:00:00'
        // console.log(`this.sidebardata[${this.sidebarIndex}].title`, this.sidebardata[this.sidebarIndex].title)
        nnobj.checkClass = this.sidebardata[this.sidebarIndex].title
        // console.log('nnobj.checkClass', nnobj.checkClass)
        nnobj.remark2 = ''
        nnobj.recordCode = ''
        nnobj.color = ''
        // const appoTitle = getSeasonDateTitle({
        //   appointmentDate: nnobj.appointmentDate,
        //   beginTime: nnobj.beginTime,
        //   endTime: nnobj.endTime
        // })
        // // console.log('==appoTitle==', appoTitle)
        // nnobj.checkClass = appoTitle || nnobj.checkClass
        // console.log('appoData_concat之前', appoData)
        appoData = appoData ? appoData.concat([nnobj]) : [nnobj]
        // console.log('appoData_concat之后', appoData)
        // console.log('这里数据就出问题了')
        // 获取排班号源初始号码排序数据
        this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex] = appoData
        // console.log(`appoData赋值给this.scheduledata[${this.scheduleIndex}].appointment[${this.sidebarIndex}]`)
        // console.log(this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex])
        const appos = await this.getAppoByTypes(this.scheduledata[this.scheduleIndex].appointment, nnobj.checkClass, this.scheduledata[this.scheduleIndex].dateFull)
        // console.log('this.scheduledata[this.scheduleIndex].appointment通过getAppoByTypes函数处理后得到appos', appos)
        this.scheduledata[this.scheduleIndex].appointment = appos
        // console.log(`appos赋值给this.scheduledata[${this.scheduleIndex}].appointment`)
        // console.log(this.scheduledata[this.scheduleIndex].appointment)
        this.scheduledatacalAppoTotal = JSON.parse(JSON.stringify(this.scheduledata)) // await this.getScheByTypes(this.scheduledata)
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
      }
    },
    // 编辑保存的数据更新，更新数据
    async editUpdate(appoObj) {
      console.log('==编辑确认按钮点击后进入editUpdate==', appoObj)
      // 编辑之前先判断，是否有多选
      if (this.isCheckedIds.length >= 1) {
        this.$confirm('当前存在勾选号源, 若进行编辑，只会一起修改被勾选号源的限制条件，请确认是否要继续?', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 找到被勾选的号源
          this.scheduledata.forEach(todayScheduleData => {
            todayScheduleData.appointment.forEach(timeFrameData => {
              timeFrameData.forEach((item, index) => {
                // 若该号源被勾选，则修改部位信息
                if (item.isChecked) {
                  item.appointmentFilters = appoObj.appointmentFilters
                  this.isChanged = true
                }
              })
            })
          })
          this.$store.dispatch('app/toggleTempVisible', false)
        }).catch(() => {})
      } else {
        // 编辑单条号源数据的时候
        const _obj = Object.assign({}, appoObj)
        let appoData = [...this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]]
        // const timeObj = this.appoRepair ? { start: '00:00', end: '24:00' } : this.sidebardata[this.sidebarIndex]
        const timeObj = this.sidebardata[this.sidebarIndex]
        const nnobj = calAppoStyleObj(timeObj, _obj, this.rowHeight)
        if (nnobj) {
          // 去除当前数据
          let appoArr = JSON.parse(JSON.stringify(this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex]))
          if (this.timeIndex >= 0) {
            appoArr.splice(this.timeIndex, 1)
          }
          appoData = appoArr ? appoArr.concat([nnobj]) : [nnobj]
          this.statusTemplate !== 'template' && this.tipFunction(appoData, nnobj)
          // 获取排班号源初始号码排序数据
          this.scheduledata[this.scheduleIndex].appointment[this.sidebarIndex] = JSON.parse(JSON.stringify(appoData))
          // 重新排号
          const appos = await this.getAppoByTypes(this.scheduledata[this.scheduleIndex].appointment, nnobj.checkClass, this.scheduledata[this.scheduleIndex].dateFull)
          this.scheduledata[this.scheduleIndex].appointment = appos
          this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
          console.log('编辑this.scheduledata', this.scheduledata)
          // 计算预约号源的当天总数
          this.calAppoTotal(this.scheduledata)
          // 判断为已改变，提交时做判断是否提交更新
          this.isChanged = true
        }
        this.$store.dispatch('app/toggleTempVisible', false)
      }
    },
    tipFunction(appoData, nnobj) {
      // 判断当前时段号源的排队号会不会超过下一个班次号源的起始排队号，若超过，提示加号源的操作者，是否要这么做
      let isOverNextAppo = false
      let isLastAppo = true
      appoData.forEach(item => {
        if (item.beginTime > nnobj.beginTime) {
          if ((nnobj.initialNum + nnobj.totalNum) > item.initialNum) {
            // this.$alert('此次操作增加号源后，将会影响到后面时段号源的排队号，请慎重修改', '系统提示', {
            //   confirmButtonText: '确定',
            //   callback: action => {
            //     // this.$message({
            //     //   type: 'info',
            //     //   message: `action: ${ action }`
            //     // });
            //   }
            // })
            isOverNextAppo = true
          }
          isLastAppo = false
        }
      })
      if (isOverNextAppo || (isLastAppo && this.isContinuityNum)) {
        let tipInfo = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在该班次的最后一个时段去增加号源。此次是否确认要修改?'
        if (!this.isContinuityNum) {
          tipInfo = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在该班次的最后一个时段去增加号源。此次是否确认要修改?'
        } else {
          tipInfo = '此次操作增加号源后，将会影响到下一个时段号源的排队号，建议在当天的最后一个时段去增加号源。此次是否确认要修改?'
        }
        this.$confirm(tipInfo, '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((e) => {
          // ......
          console.log('e', e)
          if (e == 'confirm') {
            // ......
            this.$store.dispatch('app/toggleTempVisible', false)
          } else {
            // ......
            window.location.reload()
          }
        }).catch((e) => {
          console.log('catch=>e', e)
          if (e == 'cancel') {
            window.location.reload()
          }
        })
      }
    },
    // 批量编辑保存的数据更新，更新数据
    async batchUpdate(data, index) {
      this.scheduledata[index].appointment = data
      this.scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      // this.$parent.checkedAppoData = [this.scheduledata[index]]
      // 计算预约号源的当天总数
      this.calAppoTotal(this.scheduledata)
      // 判断为已改变，提交时做判断是否提交更新
      this.isChanged = true
    },
    // 追加号源数
    setDateNumUpdate(num = 20, sidebarIndex, checkNumEditType) {
      // console.log(999999, this.scheduledata)
      // console.log('JSON.stringify(this.scheduledata)', JSON.stringify(this.scheduledata))
      const _scheduledata = this.scheduledata // JSON.parse(JSON.stringify(this.scheduledata))
      // console.log('待查看_scheduledata111', _scheduledata)
      // console.log('待查看_scheduledata_jsonStringify', JSON.stringify(_scheduledata))
      const _len = _scheduledata.length
      let count = 0
      // // console.log('_len:', _len)
      return new Promise(async resolve => {
        // console.log('待查看this.sidebardata', this.sidebardata)
        // const sdbtitle = sidebarIndex || sidebarIndex === 0 ? this.sidebardata[sidebarIndex].title : ''
        let sdbtitle = ''
        if (sidebarIndex === '') {
          sdbtitle = ''
        } else {
          this.sidebardata.forEach((item, index) => {
            if (index == sidebarIndex) {
              sdbtitle = item.title
            }
          })
        }
        // // console.log(sdbtitle)
        const start = () => {
          return new Promise(async resolve => {
            // // console.log('count:', count)
            if (count >= _len) {
              resolve()
              return false
            }
            let sdata = _scheduledata[count]
            let appointment = sdata.appointment
            const apposLen = appointment.length
            if (apposLen > 0 && sdata.checkedAll && num) {
              // 判断当前日期是否选中 checkedAll
              for (let i = 0; i < apposLen; i++) {
                const appoArr = appointment[i]
                const aLen = appoArr.length
                if ((typeof sidebarIndex === 'number' && i === sidebarIndex) || (!sidebarIndex && sidebarIndex !== 0)) {
                  for (let j = 0; j < aLen; j++) {
                    const appoObj = appoArr[j]
                    // console.log('sdbtitle', sdbtitle)
                    // console.log('appoObj.checkClass', appoObj.checkClass)
                    if (!sdbtitle || sdbtitle === appoObj.checkClass) {
                      // 判断是为追加，如果不是则赋值修改
                      appoObj.checkNum = checkNumEditType ? appoObj.checkNum * 1 + num * 1 : num * 1
                      appoObj.totalNum = getArgsCalNum(appoObj.checkNum, appoObj.reserveNum, appoObj.addNum, appoObj.callNum)
                      // 获取排班号源初始号码排序数据
                      const newSchedule = await calAppoInitialNum(appoArr, sdbtitle, this.appoContinuation, this.sidebardata, i)
                      // 重新赋值
                      sdata.appointment[i] = newSchedule
                    }
                  }
                }
              }
            }
            resolve()
          })
        }
        while (count < _len) {
          await start(_scheduledata)
          count += 1
        }
        // 计算预约号源的当天总数
        this.calAppoTotal(_scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
        // console.log('待查看_scheduledata222', _scheduledata)
        // console.log('待查看_scheduledata222_jsonStringify', JSON.stringify(this._scheduledata))
        this.scheduledata = await this.getScheByTypes(_scheduledata)
        // console.log('待查看_scheduledata333', this.scheduledata)
        // console.log('待查看_scheduledata333_jsonStringify', JSON.stringify(this.scheduledata))
        resolve(true)
      })
    },

    // 初始化
    init(data) {
      return new Promise(async resolve => {
        let _sidebardata = data.sidebardata
        this.curWeekDate = data.date
        this.checkedAll = false
        this.seasonCur = data.seasonTxt || ''
        // 计算一周的日期，weekDate
        this.weekDate = []
        // console.log('==this.curWeekDate', this.curWeekDate)
        this.weekDate = await getWeekStartEndDate(this.curWeekDate)
        // console.log('==this.weekDate==拿到本周的日期', this.weekDate)
        // 计算周的节假日
        const weekHoliday = await this.calWeekHoliday()
        let sdata = []
        const appointen = this.getAppointentArr(_sidebardata)
        // console.log('==appointen==计算班次', appointen)
        // this.weekDate ['2023-10-30', '2023-10-31', '2023-11-01', '2023-11-02', '2023-11-03', '2023-11-04', '2023-11-05']
        // 通过一周日期，给每天赋值初始值对象
        this.weekDate.forEach((item, index) => {
          const _date = item
          const _disable = new Date(item).getTime() < new Date(this.currDate).getTime()
          const _obj = {
            date: _date.substring(5).replace('-', '/'),
            dateFull: item,
            week: this.week[index],
            holiday: false,
            disable: _disable,
            season: 1,
            checkedAll: false,
            rest: weekHoliday.indexOf(_date) >= 0,
            appointmentTotal: 0,
            appointment: appointen
          }
          sdata.push(_obj)
        })
        this.scheduledata = JSON.parse(JSON.stringify(sdata))
        // console.log('##this.scheduledata##初始化了appointment##', this.scheduledata)
        this.$emit('checkedAllChange')
        // 左边时段
        this.initSidebar(_sidebardata)
        resolve()
      })
    },
    // 初始化时间轴
    initSidebar(sbd) {
      return new Promise(resolve => {
        if (sbd && typeof sbd === 'object') {
          sbd.forEach(item => {
            const resData = getInitTimeGroud(item, this.rowHeight)
            item.zanc = JSON.parse(JSON.stringify(resData))
            item.timegather = item.sidebarHide ? resData.htg : resData.stg
            item.barHeight = item.sidebarHide ? resData.hbh : resData.sbh
          })
          this.sidebardata = JSON.parse(JSON.stringify(sbd))
          console.log('this.sidebardata', this.sidebardata)
          this.$nextTick(() => {
            this.$_resizeHandler_fsc()
          })
        }
        resolve()
      })
    },
    // 计算周预约号源每天的总预约号源数，
    calAppoTotal(scheduledata) {
      return new Promise(resolve => {
        scheduledata.forEach((item, index) => {
          let total = 0
          let callNum = 0
          let zqNum = 0
          let callNumZq = 0
          // 号源统计区分上下午的对象
          let appoInfoForStatistics = {
            callNum: {},
            total: {},
            zqNum: {},
            callNumZq: {}
          }
          const appos = flattenDeep(item.appointment).filter(ap => !ap.isAddBox)
          if (appos.length > 0) {
            appos.forEach(appo => {
              // 去除已预约号源数 checkNum-检查数量 reserveNum-预留数量 initialNum-初始号码 callNum-已预约数量
              const t = appo.checkNum * 1 + appo.reserveNum * 1 + appo.addNum * 1
              total += t
              // 已预约
              if (appo.callNum) {
                callNum += appo.callNum * 1
              }
              // 增强
              const checkType = this.validAppoCheckType(appo)
              if (checkType) {
                zqNum += t
                callNumZq += appo.callNum ? appo.callNum * 1 : 0
              }
              // 上面是历史代码，下面是新增的需求，号源统计区分上下午
              if (Object.keys(appoInfoForStatistics.callNum).indexOf(appo.checkClass) > -1) {
                appoInfoForStatistics.callNum[appo.checkClass] += appo.callNum * 1
                appoInfoForStatistics.total[appo.checkClass] += t
                if (checkType) {
                  appoInfoForStatistics.zqNum[appo.checkClass] += t
                  appoInfoForStatistics.callNumZq[appo.checkClass] += appo.callNum ? appo.callNum * 1 : 0
                } else {
                  appoInfoForStatistics.zqNum[appo.checkClass] = 0
                  appoInfoForStatistics.callNumZq[appo.checkClass] = 0
                }
              } else {
                appoInfoForStatistics.callNum[appo.checkClass] = appo.callNum * 1
                appoInfoForStatistics.total[appo.checkClass] = t
                if (checkType) {
                  appoInfoForStatistics.zqNum[appo.checkClass] = t
                  appoInfoForStatistics.callNumZq[appo.checkClass] = appo.callNum ? appo.callNum * 1 : 0
                } else {
                  appoInfoForStatistics.zqNum[appo.checkClass] = 0
                  appoInfoForStatistics.callNumZq[appo.checkClass] = 0
                }
              }
            })
          }
          item.appointmentTotal = total // 日-未预约号源数
          item.appointmentCallTotal = callNum // 日-已预约号源数
          item.appointmentTotalZq = zqNum // 增强，日-未预约号源数
          item.appointmentCallTotalZq = callNumZq // 增强，日已预约号源数
          item.appoInfoForStatistics = appoInfoForStatistics
        })
        resolve()
      })
    },
    validAppoCheckType(row) {
      const _filters = row.appointmentFilters
      let checkClass = ''
      if (_filters && _filters.length > 0) {
        _filters.forEach(item => {
          if (item.parametersType === 'CheckType' && item.parametersValues.indexOf('增强') >= 0) {
            checkClass = 'check_zq'
          }
        })
      }
      return checkClass
    },
    // 计算班次,号源数组
    getAppointentArr(sidebardata) {
      let _appo = []
      let _len = sidebardata ? sidebardata.length : 1
      for (let i = 0; i < _len; i++) {
        _appo[i] = []
      }
      return _appo
    },
    // 获取、计算当前周的节假日情况
    calWeekHoliday() {
      return new Promise(async resolve => {
        if (this.statusTemplate !== 'schedule') {
          resolve([])
          return
        }
        const _week = JSON.parse(JSON.stringify(this.weekDate))
        this.monthHoliday = {}
        const _len = _week.length
        let weekHoliday = []
        for (let i = 0; i < _len; i++) {
          const ym = _week[i].substring(0, 7)
          if (!this.monthHoliday[ym]) {
            this.monthHoliday[ym] = await this.getHolidayListPost(ym)
          }
          const dIndex = this.monthHoliday[ym].findIndex(item => item.holiday.substring(0, 10) === _week[i])
          if (dIndex >= 0) {
            weekHoliday.push(_week[i])
          }
        }
        resolve(weekHoliday)
      })
    },
    // 获取月节假日
    getHolidayListPost(month) {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.hospitalCode,
          Month: month
        }
        let resMonth = []
        await getHolidayList(params).then(res => {
          if (res && res.code === 10000) {
            resMonth = res.content.list
          }
        })
        resolve(resMonth)
      })
    },
    initData(data) {
      const appos = data // JSON.parse(JSON.stringify(data))
      return appos
    },
    // 数据推入判断执行方法
    appoPull(appoData, isChanged) {
      // console.log('appoPull=>into')
      appoData.forEach(item => {
        item.isChecked = false
      })
      // console.log('拿到所有的号源数据appoPull', appoData)
      const initData = this.initData(JSON.parse(JSON.stringify(appoData)))
      // console.log('initData_out', initData)
      const _appoData = [...initData]
      // console.log('处理过后的号源数据_appoData', JSON.stringify(_appoData))
      this.scheduledata = JSON.parse(JSON.stringify(_appoData))
    },
    // 数据导入，会覆盖原来的预约时段
    async appoImport(ImportAppointmentData, isWeek) {
      // 1、遍历导入数据
      // 2、计算导入数据的日期，是星期几 ‘scheduleIndex’
      // 3、遍历导入的日数据
      // 4、计算时段时间所在时段‘sidebarIndex’，如：上午班、下午班。且导入时段数据不超出所在的时段最大最小时间范围。
      // 5、根据计算的 ‘scheduleIndex’、‘sidebarIndex’，计算日单条时段数据与所在日期时段的原始数据的交集情况
      // 6、根据计算的交集情况，如有交集，删除交集的原始数据。
      // 7、添加当前导入数据到计算出来的‘scheduleIndex’、‘sidebarIndex’日期时段。
      const IAppoData = JSON.parse(JSON.stringify(ImportAppointmentData.map(ia => ia.filter(a => !a.isAddBox))))
      const _sidebardata = this.sidebardata
      const _scheduledata = JSON.parse(JSON.stringify(this.scheduledata))
      return new Promise(async resolve => {
        if (isWeek) {
          _scheduledata.forEach((item, index) => {
            // 当天的数据过滤，改为直接替换导入数据，清空当前之前的数据
            _scheduledata[index].appointment = this.getAppointentArr(_sidebardata)
          })
        }
        // console.log('IAppoData ===', IAppoData)
        IAppoData.forEach((iAppoDayList) => {
          if (iAppoDayList.length) {
            // // console.log('iAppoDayList ============', iAppoDayList)
            // 星期几
            const scheduleIndex = _scheduledata.findIndex(sche => sche.week === iAppoDayList[0].week)
            if (!isWeek) {
              _scheduledata[scheduleIndex].appointment = this.getAppointentArr(_sidebardata)
            }
            // 导入数据的 一天数据遍历
            iAppoDayList.forEach((iAppo) => {
              // // console.log('iAppo:=============', iAppo)
              // 加一个检查时间 appointmentDate: "2021-05-26 00:00:00"
              iAppo.appointmentDate = _scheduledata[scheduleIndex].dateFull + ' 00:00:00'
              iAppo.id = !iAppo.id && iAppo.id !== 0 ? 0 : iAppo.id
              iAppo.timestamp = new Date().getTime() + Math.random()

              let IminTime = iAppo.beginTime
              let ImaxTime = iAppo.endTime
              let ImaxMin = ImaxTime.split(':')[0] * 60 + ImaxTime.split(':')[1] * 1
              let IminMin = IminTime.split(':')[0] * 60 + IminTime.split(':')[1] * 1
              let sidebarIndex = -1
              // 班次名称判断转换
              const appoTitle = getSeasonDateTitle({
                appointmentDate: iAppo.appointmentDate,
                beginTime: iAppo.beginTime,
                endTime: iAppo.endTime,
                checkClassData: _sidebardata
              })
              // console.log('班次名称判断转换appoTitle', appoTitle)
              iAppo.checkClass = appoTitle || iAppo.checkClass
              // console.log('_sidebardata====>', _sidebardata)
              _sidebardata.forEach((sbd, sbIndex) => {
                // console.log('sbd.end====>', sbd.end)
                let minTime = sbd.start
                let maxTime = sbd.end
                let maxMin = maxTime.split(':')[0] * 60 + maxTime.split(':')[1] * 1
                let minMin = minTime.split(':')[0] * 60 + minTime.split(':')[1] * 1
                if (IminMin >= minMin && ImaxMin <= maxMin) {
                  // 判断星期几、判断时段内是否超出
                  sidebarIndex = sbIndex
                }
              })
              // // console.log('scheduleIndex:====', scheduleIndex)
              // // console.log('sidebarIndex:====', sidebarIndex)
              if (sidebarIndex >= 0) {
                let oldAppo = _scheduledata[scheduleIndex].appointment[sidebarIndex]
                const oldAppoLen = oldAppo.length
                if (oldAppoLen > 0) {
                  let lapNum = -1
                  oldAppo.forEach((oAppo, oAppoIndex) => {
                    let minTime = oAppo.beginTime
                    let maxTime = oAppo.endTime
                    let maxMin = maxTime.split(':')[0] * 60 + maxTime.split(':')[1] * 1
                    let minMin = minTime.split(':')[0] * 60 + minTime.split(':')[1] * 1
                    if (!(ImaxMin <= minMin && IminMin < minMin) && !(ImaxMin > maxMin && IminMin >= maxMin)) {
                      // 判断时段区间的交集情况
                      // 赋值交集数据的索引
                      lapNum = oAppoIndex
                    }
                  })
                  // 如有交集，删除原来交集数据
                  if (lapNum >= 0) {
                    oldAppo.splice(lapNum, 1)
                  }
                  // 添加导入数据
                  oldAppo.push({ ...iAppo })
                } else {
                  // 添加导入数据
                  oldAppo.push({ ...iAppo })
                }
              } else {
                // console.log('导入时段时间不在当前时段范围！')
              }
            })
            // // console.log('scheduleIndex:====', scheduleIndex)
          }
        })
        // // console.log('_scheduledata:====', _scheduledata)
        // await getScheduleAppoSametype(_scheduledata)
        // 号源重新插入
        let appodata = []
        _scheduledata.forEach(sche => {
          let iScheAppoArr = sche.appointment
          iScheAppoArr = flattenDeep(iScheAppoArr)
          appodata.push(iScheAppoArr)
        })
        appodata = flattenDeep(appodata)
        this.appoPull(appodata, true)

        // this.scheduledata = JSON.parse(JSON.stringify(_scheduledata))
        // 计算预约号源的当天总数
        this.calAppoTotal(this.scheduledata)
        // 判断为已改变，提交时做判断是否提交更新
        this.isChanged = true
        this.sidebarHideShow()
        resolve(true)
      })
    },

    // 设置初始展示数据，模拟数据
    setInitData() {
      const sideLen = this.sidebardata.length
      const scheLen = this.scheduledata.length
      for (let i = 0; i < sideLen; i++) {
        for (let j = 0; j < scheLen; j++) {
          const tg = this.sidebardata[i].timegather
          const timeLen = this.sidebardata[i].timegather.length
          const astatus = (Math.floor(Math.random() * 10) % 5) + ''
          for (let t = 0; t < timeLen; t++) {
            originObj.beginTime = tg[t].time.split('-')[0]
            originObj.endTime = tg[t].time.split('-')[1]
            originObj.initialNum = Math.floor(Math.random() * 30)
            originObj.checkNum = Math.floor(Math.random() * 30)
            originObj.appointmentStatus = astatus
            this.quickTempObjFul = Object.assign({}, originObj)
            this.appoAdd({ sidebarIndex: i, scheduleIndex: j, timeIndex: t })
          }
        }
      }
      this.quickTempObjFul = null
      originObj.appointmentStatus = ''
    },
    sidebarHideChange(index, type) {
      // // console.log('sidebarHideChange', index)
      // type 判断是否展开列表，在数据加载的时候传 type:true 默认有数据列表展开
      this.sidebardata[index].sidebarHide = type ? false : !this.sidebardata[index].sidebarHide
      // // console.log('sidebarHideChange', this.sidebardata[index])
      if (!this.sidebardata[index].sidebarHide) {
        this.sidebardata[index].barHeight = this.sidebardata[index].zanc.sbh
        this.sidebardata[index].timegather = this.sidebardata[index].zanc.stg
      } else {
        this.sidebardata[index].barHeight = this.sidebardata[index].zanc.hbh
        this.sidebardata[index].timegather = this.sidebardata[index].zanc.htg
      }
      this.sidebardata = JSON.parse(JSON.stringify(this.sidebardata))
      // // console.log(this.sidebardata[index].barHeight)
    },
    // 展开收起
    sidebarHideShow() {
      const appointent = this.getAppointentArr(this.sidebardata)
      const scheLen = this.scheduledata.length
      for (let i = 0; i < appointent.length; i++) {
        let count = 0
        for (let j = 0; j < scheLen; j++) {
          count += this.scheduledata[j].appointment[i].length
        }
        if (count > 0) {
          this.sidebarHideChange(i, true)
        }
      }
    },
    // 计算时段可以加的最小，最大号源区间
    getInitialMinMaxNum(beginTime, endTime) {
      // console.log('==beginTime', beginTime)
      // console.log('=============getInitialMinMaxNum_begin==============')
      // // console.log(beginTime, endTime)
      const sbIdx = this.sidebarIndex
      const sdIdx = this.scheduleIndex
      let bTime = beginTime ? beginTime.split(':')[0] * 60 + beginTime.split(':')[1] * 1 : 0
      let eTime = endTime ? endTime.split(':')[0] * 60 + endTime.split(':')[1] * 1 : 0

      const appoArr = this.scheduledata[sdIdx].appointment[sbIdx]
      // // console.log(appoArr)
      let minNum = 0 // 最小值为，所有值相加
      let maxNum = 0 // 最大值为，初始值
      if (appoArr.length > 0) {
        let minBTime = bTime + eTime
        let minCurrTime = 0
        let maxBTime = bTime + eTime
        let maxCurrTime = 0
        // console.log('appoArr', appoArr)
        appoArr.forEach(item => {
          // console.log('item.beginTime', item.beginTime)
          // console.log('item', item)
          if (item.beginTime < beginTime) {
            const bt = item.beginTime.split(':')[0] * 60 + item.beginTime.split(':')[1] * 1
            const et = item.endTime.split(':')[0] * 60 + item.endTime.split(':')[1] * 1
            const iTime = bt + et
            // console.log('minBTime', minBTime)
            // console.log('iTime', iTime)
            // console.log('minCurrTime', minCurrTime)
            // console.log('item.initialNum', item.initialNum)
            // console.log('item.checkNum', item.checkNum)
            // console.log('item.reserveNum', item.reserveNum)
            // console.log('item.addNum', item.addNum)
            if (minBTime > iTime && minCurrTime < iTime) {
              minCurrTime = iTime
              minNum = (item.initialNum * 1) + (item.checkNum * 1) + (item.reserveNum * 1) + (item.addNum * 1)
            }
            // console.log('maxBTime', maxBTime)
            // console.log('maxCurrTime', maxCurrTime)
            if (maxBTime < iTime && (iTime < maxCurrTime || maxCurrTime === 0)) {
              maxCurrTime = iTime
              maxNum = (item.initialNum * 1)
            }
            // if (minBTime > iTime && minCurrTime < iTime) {
            //   minCurrTime = iTime
            //   minNum = (item.initialNum * 1)
            // }
            // // console.log('maxBTime', maxBTime)
            // // console.log('maxCurrTime', maxCurrTime)
            // if (maxBTime < iTime && (iTime < maxCurrTime || maxCurrTime === 0)) {
            //   maxCurrTime = iTime
            //   maxNum = (item.initialNum * 1) + (item.checkNum * 1) + (item.reserveNum * 1) + (item.addNum * 1)
            // }
          }
          // console.log('=============getInitialMinMaxNum_End==============')
        })
      }
      // console.log('minNum, maxNum', minNum, maxNum)
      return { minNum, maxNum }
    },
    // 计算 sidebarIndex
    calSidebarIndex(appoInfo) {
      let sidebarIndex = -1
      if (!appoInfo) return sidebarIndex
      this.sidebardata.forEach((item, index) => {
        const st = item.start.split(':')[0] * 60 + item.start.split(':')[1] * 1
        const et = item.end.split(':')[0] * 60 + item.end.split(':')[1] * 1
        const ost = appoInfo.beginTime.split(':')[0] * 60 + appoInfo.beginTime.split(':')[1] * 1
        const oet = appoInfo.endTime.split(':')[0] * 60 + appoInfo.endTime.split(':')[1] * 1
        if (ost >= st && (oet <= et || this.appoRepair)) {
          // 判断班次，获取班次索引
          sidebarIndex = index
        }
      })
      return sidebarIndex
    },
    // 窗体大小变化，自动改变列表最大值
    $_resizeHandler_fsc() {
      const fscRef = this.$refs.fullscheduleContainer
      if (fscRef) {
        this.$nextTick(() => {
          // this.fscHeight = fscRef.offsetTop + 25
          if (this.from !== 'numberRules') {
            this.fscHeight = fscRef.getBoundingClientRect().top + 25
            this.fscStyle.height = `calc(100vh - ${fscRef.getBoundingClientRect().top + 25}px)`
          }
          // // console.log(fscRef.getBoundingClientRect().top)
          // // console.log(fscRef.offsetWidth)
        })
      }
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.$_resizeHandler_fsc)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.$_resizeHandler_fsc)
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/fullschedule.scss';

</style>
